import { MessgaeService } from './../../../../../@core/services/message/messgae.service';
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { DialogService } from 'ng-devui';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Message, Notification, Todo } from 'src/app/@core/data/noticeData';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { ReviewDocComponent } from 'src/app/pages/basic-data/user-center/review-doc/review-doc.component';

@Component({
  selector: 'da-header-notice',
  templateUrl: './header-notice.component.html',
  styleUrls: ['./header-notice.component.scss'],
})
export class HeaderNoticeComponent implements OnInit {
  @Output() countEvent = new EventEmitter<number>();

  private destroy$ = new Subject<void>();

  tabActiveID: string | number = 'notice';

  tabTitles: any;

  i18nValues: any;

  notifications: Notification[] = [];
  messages: Message[] = [];
  todos: Todo[] = [];
  noticeLength = 0;
  messageLength = 0;
  user: any
  get noticeTitle() {
    return `${this.tabTitles.notice}(${this.noticeLength})`;
  }
  get messageTitle() {
    return `${this.tabTitles.message}(${this.messageLength})`;
  }
  constructor(
    private translate: TranslateService,
    private MessgaeService: MessgaeService,
    private DialogService: DialogService,
    private ReviewRolesService: ReviewRolesService,
    private route: Router,
  ) {}
  ngOnInit() {
    let userinfo = localStorage.getItem('userinfo');
    if (!userinfo) {
      userinfo = sessionStorage.getItem('userinfo');
    }
    this.user = userinfo ? JSON.parse(userinfo) : null;
    this.tabTitles = {
      notice: '未读消息',
      message: '全部消息',
      todo: '待办事项',
    };
    const recipientId = Number(localStorage.getItem('id'));
    this.fetchMessages(recipientId);
    setInterval(() => {
      this.fetchMessages(recipientId);
    }, 30000);
  }
  handleNoticeClick(type: string, id: any) {
    const recipientId = Number(localStorage.getItem('id'));
    if (type === 'notice') {
      this.MessgaeService.SetMessageAsRead({
        messageId: id,
        userId: recipientId,
      }).subscribe((res: any) => {
        this.fetchMessages(recipientId);
      });
    }
  }
  allRead(type: string) {
    const recipientId = Number(localStorage.getItem('id'));
    if (type === 'notice') {
      this.MessgaeService.GetPagedMessage({
        pageIndex: 1,
        pageSize: 999,
        readStatus: '未读',
        recipientId: recipientId,
      }).subscribe((res: any) => {
        const messageIds = this.notifications.map(
          (notification) => notification.messageId
        );
        this.MessgaeService.SetBatchMessageAsRead(
          { userId: recipientId },
          messageIds
        ).subscribe((res: any) => {
          this.fetchMessages(recipientId);
        });
      });
    }
    if (type === 'message') {
      this.messages = [];
      this.countEvent.emit(this.noticeLength);
    }
    if (type === 'todo') {
      this.todos = [];
      this.countEvent.emit(this.noticeLength);
    }
  }

  extractOrderNumbers(text: string): string[] {
    // 匹配以 "单号:" 开头，末尾是数字序列的单号
    const orderNumberPattern = /单号:([A-Z0-9-]*\d+)/g;
    const matches = [];
    let match;
    while ((match = orderNumberPattern.exec(text)) !== null) {
      matches.push(match[1]);
    }
    return matches;
  }
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
  fetchMessages(recipientId: number): void {
    this.MessgaeService.GetPagedMessage({
      pageIndex: 1,
      pageSize: 20,
      readStatus: '未读',
      recipientId: recipientId,
    }).subscribe((res: any) => {
      this.notifications = res.items;
      this.noticeLength = res.totalCount;
      setTimeout(() => {
        this.countEvent.emit(res.totalCount);
      });
    });
    this.MessgaeService.GetPagedMessage({
      pageIndex: 1,
      pageSize: 20,
      recipientId: recipientId,
    }).subscribe((res: any) => {
      this.messages = res.items;
      this.messageLength = res.totalCount;
    });
  }
  splitMessageContent(content: string): {
    before: string;
    orderNumber: string;
    after: string;
    type: string;
  } {
    const orderNumberPattern =
      /单号:([A-Z0-9-]*\d)(等待审核中|已由其他人员审核通过|您有一条新的单据待审核|审核不通过)?/;
    const match = content.match(orderNumberPattern);
    let type = this.setType(content);
    if (match) {
      const [fullMatch, orderNumber, after] = match;
      const before = content.split(fullMatch)[0];
      return { before, orderNumber, after: after ? after : '', type };
    }
    return { before: content, orderNumber: '', after: '', type };
  }
  generateLink(type: string): string {
    const routeMap: { [key: string]: string } = {
      采购订单审核: '/pages/purchase/purchase-order',
      采购需求单审核: '/pages/purchase/purchase-require',
      采购到货单审核: '/pages/purchase/purchase-arrival',
      采购退货单审核: '/pages/purchase/purchase-return',
      采购委外单审核: '/pages/purchase/purchase-outsource',
      委外到货单审核: '/pages/purchase/purchase-outsource-arrival',
      委外退货单审核: '/pages/purchase/purchase-outsource-return',
      销售报价单审核: '/pages/sales-master/sales-quotation-order',
      销售订单审核: '/pages/sales-master/sales-order',
      销售发货单审核: '/pages/sales-master/sales-Invoice',
      销售退货单审核: '/pages/sales-master/sales-return-order',
    };
    return routeMap[type] || '';
  }
  setType(content: string): string {
    const typeMap: { [key: string]: string } = {
      采购订单: '采购订单审核',
      采购需求单: '采购需求单审核',
      采购到货单: '采购到货单审核',
      采购退货单: '采购退货单审核',
      采购委外单: '采购委外单审核',
      委外到货单: '委外到货单审核',
      委外退货单: '委外退货单审核',
      销售报价单: '销售报价单审核',
      销售订单: '销售订单审核',
      销售发货单: '销售发货单审核',
      销售退货单: '销售退货单审核',
    };
    for (const key in typeMap) {
      if (content.includes(key)) {
        return typeMap[key];
      }
    }
    return '审核类型';
  }
  handleClean(type: string) {
    if (type === 'message') {
      this.MessgaeService.GetPagedMessage({
        pageIndex: 1,
        pageSize: 999,
        recipientId: Number(localStorage.getItem('id')),
      }).subscribe((res: any) => {
        const messageIds = this.messages.map(
          (notification) => notification.messageId
        );
        this.MessgaeService.DeleteBatchMessage(
          {
            userId: Number(localStorage.getItem('id')),
          },
          messageIds
        ).subscribe((res: any) => {
          this.fetchMessages(Number(localStorage.getItem('id')));
        });
      });
    }
  }
  config = {
    id: 'custom',
    width: '90vw',
    maxHeight: '90vh',
    backdropCloseable: true,
    zIndex: 1055,
  }; //弹窗配置
  clickCode(code: string, type: string, id: any, dialogtype?: string) {
    const results = this.DialogService.open({
      ...this.config,
      content: ReviewDocComponent,
      dialogtype: dialogtype,
      data: {
        code: code,
        type: type,
      },
      onClose: () => {
        this.readMessage(id);
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '通过',
          handler: ($event: Event) => {
            this.ReviewRolesService.ApproveNode(
              results.modalContentInstance.approvalNodeId,
              code
            ).subscribe((res: any) => {
              results.modalInstance.hide();
            });
          },
        },
        {
          cssClass: 'danger',
          text: '驳回',
          handler: ($event: Event) => {},
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  readMessage(id: any) {
    const recipientId = Number(localStorage.getItem('id'));
    this.MessgaeService.SetMessageAsRead({
      messageId: id,
      userId: recipientId,
    }).subscribe((res: any) => {
      this.fetchMessages(recipientId);
    });
  }
  more(type: string) {
    this.route.navigate(['/pages/basicdata/userCenter', this.user.employeeCode,type]);
  }
}
